package com.alston.rest.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alston.rest.common.Require;
import com.alston.rest.common.TokenManager;
import com.alston.rest.common.bean.Code;
import com.alston.rest.common.bean.NormalResponse;
import com.alston.rest.common.utils.MD5Utils;
import com.alston.rest.controller.base.BaseController;
import com.alston.rest.interceptor.JwtTokenInterceptor;
import com.alston.rest.model.User;
import com.alston.rest.service.UserService;
import com.alston.rest.service.impl.UserServiceImpl;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;

@Before(JwtTokenInterceptor.class)
public class UserController  extends BaseController{
	private static Logger log = Logger.getLogger("LoginController");
	
	UserService userService = new UserServiceImpl();
	
	/**
	 * 登录
	 * */
	@Clear
	public void login(){  
		String username = getPara("username");
		String password = getPara("password");
		
		//校验参数,确保不能为空
		if (!notNull(Require.me().put(username, "用户名不能为空！").put(password, "密码不能为空！") )) {
			return;
		}
		User user = userService.findUserByUsername(username);
		if(null != user){
			if(user.getInt("accountStatus")==2){
				renderFailed("账号已失效，请联系管理员。");
				return;
			}else if(user.getInt("accountStatus")==0){
				renderFailed("账号已被禁用，请联系管理员。");
				return;
			}else{
				if(!user.getStr("password").equals(MD5Utils.encryptPwd(password))){
					renderFailed("用户名或密码错误，请重新输入。");
					return;
				}
			}
		}else{
			renderFailed("账号不存在");
			return;
		}
		
		//登录成功，生成jwt的token
		String token = TokenManager.createJwtToken(user.getLong("userId").toString());
		log.info("本次登录用户id为:"+user.getLong("userId")+",token为："+token);
		TokenManager.generateTokenInfo(token,user);
		
		NormalResponse response = new NormalResponse();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("token", token);
		response.setCode(Code.SUCCESS).setMsg("登录成功！");
		response.setResult(resultMap);
		renderJson(response);   
    } 
	
	
	/**
	 * 获取用户信息
	 * */
	public void userinfo(){  
		User user = getAttr("user");
		NormalResponse response = new NormalResponse();
		response.setCode(Code.SUCCESS).setMsg("OK！");
		response.setResult(user);
		renderJson(response);
    } 
	
	
}
